<template>
  <view class="address-container">
    <view class="form-container">
      <view class="form-item">
        <text class="icon">📍</text>
        <text class="label">省市区</text>
        <input class="input" placeholder="省市区（必填）" v-model="address" />
      </view>
      
      <view class="form-item">
        <text class="icon">🏠</text>
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、小区、楼层等（必填）" v-model="detailAddress" />
      </view>
      
      <view class="form-item">
        <text class="icon">👤</text>
        <text class="label">联系人</text>
        <input class="input" placeholder="名字（必填）" v-model="contactName" />
      </view>
      
      <view class="form-item">
        <text class="icon">📱</text>
        <text class="label">联系电话</text>
        <input class="input" placeholder="手机号码（必填）" v-model="phone" type="number" />
      </view>
    </view>
    
    <view class="confirm-btn" @click="handleSubmit">保存地址</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      id: null,
      address: '',
      detailAddress: '',
      contactName: '',
      phone: '',
      isSelectMode: false
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.loadAddressData();
    }
    if (options.select === 'true') {
      this.isSelectMode = true;
    }
  },
  methods: {
    loadAddressData() {
      const addressList = uni.getStorageSync('addressList') || [];
      const address = addressList.find(item => item.id == this.id);
      
      if (address) {
        this.address = address.fullAddress || '';
        this.detailAddress = address.detailAddress || '';
        this.contactName = address.contactName || '';
        this.phone = address.phone || '';
      }
    },
    
    handleSubmit() {
      // 验证必填项
      if (!this.address || !this.detailAddress || !this.contactName || !this.phone) {
        uni.showToast({ title: '请填写所有必填项', icon: 'none' });
        return;
      }
      
      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return;
      }
      
      const isUpdate = !!this.id; 
      const apiUrl = isUpdate 
        ? `https://billiards.cqtrust.cn/addresses/${this.id}` 
        : "https://billiards.cqtrust.cn/addresses";
      
      const requestData = {
        address: this.address,
        details: this.detailAddress,
        contact_name: this.contactName,
        contact_phone: this.phone
      };
      
      this.$http[isUpdate ? 'put' : 'post'](apiUrl, requestData)
        .then((res) => {
          const { code, msg, data } = res;
          
          uni.showToast({
            title: msg,
            icon: 'none'
          });
          
          if (code == 1 || code == 200) {
            // 本地存储
            let addressList = uni.getStorageSync('addressList') || [];
            const newAddress = {
              id: data.id || this.id,
              fullAddress: this.address,
              detailAddress: this.detailAddress,
              contactName: this.contactName,
              phone: this.phone
            };
            
            if (isUpdate) {
              // 更新现有地址
              const index = addressList.findIndex(item => item.id == this.id);
              if (index !== -1) {
                addressList[index] = newAddress;
              }
            } else {
              // 添加新地址
              addressList.unshift(newAddress);
            }
            
            uni.setStorageSync('addressList', addressList);
            
            // 如果是选择模式，返回地址信息
            if (this.isSelectMode) {
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              if (prevPage && prevPage.$vm && prevPage.$vm.setSelectedAddress) {
                prevPage.$vm.setSelectedAddress(newAddress);
              }
              uni.navigateBack();
            } else {
              // 不是选择模式，直接返回
              uni.navigateBack();
            }
          }
        })
        .catch((error) => {
          console.error('保存地址失败:', error);
          uni.showToast({
            title: '保存地址失败，请重试',
            icon: 'none'
          });
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.address-container { 
  padding: 30rpx; 
  background: #f5f5f5; 
  min-height: 100vh; 
}

.form-container {
  background: #fff; 
  border-radius: 12rpx; 
  padding: 0 30rpx; 
  margin-bottom: 30rpx;
  
  .form-item {
    padding: 30rpx 0; 
    border-bottom: 1rpx solid #f0f0f0; 
    display: flex; 
    align-items: center;
    
    &:last-child { 
      border: none; 
    }
    
    .icon { 
      color: #fdad18; 
      margin-right: 15rpx; 
      font-size: 36rpx; 
    }
    
    .label { 
      font-size: 32rpx; 
      color: #333; 
      width: 150rpx; 
    }
    
    .input { 
      flex: 1; 
      font-size: 28rpx; 
      padding: 15rpx 0; 
      margin-left: 20rpx; 
    }
  }
}

.confirm-btn {
  background: #fdad18; 
  color: #fff; 
  text-align: center; 
  padding: 25rpx; 
  border-radius: 50rpx; 
  font-size: 32rpx; 
  font-weight: bold;
}
</style>